/*
https://leetcode-cn.com/problems/hand-of-straights/solution/yi-shou-shun-zi-by-leetcode-solution-4lwn/
 */
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class Solution846 {
    public boolean isNStraightHand(int[] hand, int groupSize) {
        int n=hand.length;
        if (n%groupSize!=0){
            return false;
        }
        Arrays.sort(hand);
        Map<Integer,Integer> map=new HashMap<>();
        for (int i : hand) {
            map.put(i,map.getOrDefault(i,0)+1);
        }
        for (int i : hand){
            if (!map.containsKey(i)){
                continue;
            }
            for (int j=0;j<groupSize;j++){
                int temp=map.getOrDefault(i+j,0);
                if (temp==0){
                    return false;
                }else if (temp==1){
                    map.remove(i+j);
                }else{
                    map.put(i+j,temp-1);
                }
            }
        }
        return true;
    }

    public static void main(String[] args) {
        System.out.println(new Solution846().isNStraightHand(new int[]{1,2,3,6,2,3,4,7,8},3));
    }
}
